import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ActivatedRoute}  from "@angular/router";
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../../bi.service';

@Component({
  selector: 'apes-apes-keep-insurance-order-store',
  templateUrl: './apes-keep-insurance-order-store.component.html',
  styleUrls: ['apes-keep-insurance-order-store.component.scss']
})
export class ApesKeepInsuranceOrderStoreComponent implements OnInit {
  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = window.innerHeight - 480 + 'px';

  topData: any[];     // 柱形图相关
  lastData: any[];

  endDate = null;      // 默认结束时间
  startDate = null;    // 默认开始时间 当天的前7天

  endTime = null;      // 传的结束时间
  startTime = null;    // 传的起始时间

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData: any;
  companyList: any[];

  startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  };
  endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  };

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private routerInfo: ActivatedRoute,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "门店名称", field: 'MDMC'},
      {headerName: "累计销售单数", field: 'XSDS'},
      {headerName: "应续保数", field: 'YXB'},
      {headerName: "应续保金额", field: 'YXBJE'},
      {headerName: "已续保数", field: 'XU'},
      {headerName: "已续保金额", field: 'XUBJE'},
      {headerName: "新保单数", field: 'XIN'},
      {headerName: "新保金额", field: 'XINBJE'},
      {headerName: "续保率", field: 'XBL'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (0 * 24 * 60 * 60 * 1000));
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this.submit();
  }

  submit() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    // 传的时间 进行转换
    // 传的时间 进行转换
    if(this.endDate !== null && this.startDate !== null) {
      this.startTime = (this.startDate.toISOString()).slice(0, 10);
      this.endTime = (this.endDate.toISOString()).slice(0, 10);
      this.getTablesData();
    }else {
      this.msg.error('日期必填，不能为空！');
    }
  }

  getTablesData() {
    let data = { 'interfaceMethod': 'ipmBusinessStatementService.getXbfx_MD', 'pdata': { 'ZDRQ_SJ': this.startTime ,'SKRQ_SJ': this.endTime, 'companyId': this.companyList} };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            this.rowData = data;
            //柱型图 数据获取
            // 前十
            data = data.sort(this.sortarr('XU'));
            this.topData = [];
            const topList = data.slice(0, 10);
            this.topData = topList.map((value) => {
              return { x: value['MDMC'], y: value['XU'] };
            });
            // 后十
            this.lastData = [];
            const lastList = data.slice(data.length - 10, data.length).reverse();
            this.lastData = lastList.map((value) => {
              return { x: value['MDMC'], y: value['XU'] };
            });
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }

}
